<template>
  <view class="symptom-container">
    <!-- 欢迎页：AI症状检查 -->
    <view v-if="stage === 'welcome'" class="welcome-page">
      <view class="welcome-back" @click="fabBack">←</view>
      <view class="welcome-hero-wrap">
        <image class="welcome-hero" :src="welcomeImg" mode="widthFix" @error="onWelcomeImgError"></image>
        <view class="hero-fab" @click="fabBack">
          <text class="back-icon">←</text>
        </view>
      </view>
      <view class="welcome-title">AI症状检查</view>
      <view class="welcome-subtitle">立即使用我们的 AIML 技术检查您的症状。</view>
      <button class="primary-btn welcome-btn" @click="startAssessment">检查我的症状 ✓</button>
    </view>

    <!-- 方式选择：步骤1 -->
    <view v-else-if="stage === 'method'" class="method-page">
      <view class="steps">
        <view class="step active"></view>
        <view class="step"></view>
        <view class="step"></view>
        <view class="step"></view>
      </view>
      <view class="method-title">您希望如何检查您的症状？</view>
      <view class="method-cards">
        <view class="method-card" :class="{ active: methodChoice === 'ai' }" @click="selectMethod('ai')">
          <view class="card-icon">🤖</view>
          <view class="card-title">AI评估</view>
          <view class="card-desc">根据我们的 AI 医学资料与助手互动完成评估</view>
        </view>
        <view class="method-card" :class="{ active: methodChoice === 'manual' }" @click="selectMethod('manual')">
          <view class="card-icon">📝</view>
          <view class="card-title">与人工智能聊天机器人</view>
          <view class="card-desc">跟AI对话聊天</view>
        </view>
      </view>
      <view class="start-footer">
        <view class="btn-spacer"></view>
        <button class="primary-btn" :disabled="!methodChoice" @click="continueFromMethod">继续 →</button>
      </view>
      <view class="fab" @click="fabBack">
        <text class="back-icon">←</text>
      </view>
    </view>

    <!-- 启动页：部位选择 -->
    <view v-else-if="stage === 'start'" class="start-page">
      <view class="start-header">
        <view class="logo-mark"></view>
      </view>
      <view class="start-title">您身体部位的哪个症状最困扰您？</view>
      <view class="start-options">
        <button
          v-for="bp in bodyParts"
          :key="bp.value"
          class="start-option"
          @click="chooseBodyPart(bp.value)"
        >
          <text class="label">{{ bp.label }}</text>
          <text class="arrow">→</text>
        </button>
      </view>
      <view class="fab" @click="fabBack">
        <text class="back-icon">←</text>
      </view>
    </view>

    <!-- 问诊流程 -->
    <view v-else-if="stage === 'qa'" class="qa-page">
      <view class="qa-header">
        <view class="progress-text">进度 {{ currentIndex + 1 }}/{{ visibleQuestions.length }}</view>
        <view class="progress">
          <view class="bar" :style="{ width: progress + '%' }"></view>
        </view>
      </view>

      <scroll-view class="qa-body" scroll-y>
        <!-- 机器提问气泡 -->
        <view class="bubble ai">
          <view class="bubble-avatar">🤖</view>
          <view class="bubble-content">
            <view class="q-title">{{ currentTitle }}</view>
            <view class="q-desc" v-if="currentQuestion.desc">{{ currentQuestion.desc }}</view>

            <!-- 选项区域 -->
            <view v-if="currentQuestion.type === 'single'" class="options">
              <button
                v-for="(opt, i) in currentQuestion.options"
                :key="i"
                class="option"
                :class="{ active: isSelected(opt.value) }"
                @click="chooseSingle(opt.value)"
              >{{ opt.label }}</button>
            </view>

            <view v-else-if="currentQuestion.type === 'multiple'" class="options">
              <button
                v-for="(opt, i) in currentQuestion.options"
                :key="i"
                class="option"
                :class="{ active: isSelected(opt.value) }"
                @click="toggleMultiple(opt.value)"
              >{{ opt.label }}</button>
            </view>

            <view v-else-if="currentQuestion.type === 'level'" class="level-list">
              <view
                v-for="(opt, i) in currentQuestion.options"
                :key="i"
                class="level-item"
                :class="{ active: isSelected(opt.value) }"
                @click="chooseSingle(opt.value)"
              >
                <view class="badge">{{ opt.value }}</view>
                <view class="text">{{ opt.label }}</view>
              </view>
            </view>

            <view v-else-if="currentQuestion.type === 'input'" class="input-wrap">
              <input class="text-input" v-model="inputValue" :placeholder="currentQuestion.placeholder || '请输入'" />
            </view>
          </view>
        </view>

        <!-- 用户回答回显气泡 -->
        <view v-if="answers[currentQuestion.id] && answers[currentQuestion.id].length" class="bubble user">
          <view class="bubble-avatar">👤</view>
          <view class="bubble-content">
            <text>{{ renderAnswer(answers[currentQuestion.id]) }}</text>
          </view>
        </view>
      </scroll-view>

      <view class="qa-footer">
        <button class="ghost-btn" @click="onLeftClick">{{ currentIndex === firstActiveIndex ? '返回' : '上一步' }}</button>
        <button class="primary-btn" :disabled="!canNext" @click="next">{{ isLast ? '完成评估' : '下一步' }}</button>
      </view>
    </view>

    <!-- 结果页 -->
    <view v-else-if="stage === 'result'" class="result-page">
      <view class="score-card">
        <view class="score">{{ result.score }}</view>
        <view class="score-label">综合健康评分</view>
        <view class="score-desc">基于您的回答生成，仅供参考</view>
      </view>

      <view class="section">
        <view class="section-title">可能关联的疾病</view>
        <view class="disease-list">
          <view v-for="(item,idx) in result.diseases" :key="idx" class="disease-item">
            <view class="name">{{ item.name }}</view>
            <view class="prob">
              <view class="prob-bar" :style="{ width: item.prob + '%' }"></view>
              <text class="prob-text">{{ item.prob }}%</text>
            </view>
          </view>
        </view>
      </view>

      <view class="section">
        <view class="section-title">建议与指引</view>
        <view class="advice" v-for="(line, i) in result.advices" :key="i">• {{ line }}</view>
      </view>

      <view class="section">
        <view class="section-title">AI分析报告</view>
        <view v-if="aiLoading" class="advice">AI 正在生成建议...</view>
        <view v-else-if="aiError" class="advice">{{ aiError }}</view>
        <view v-else class="advice">{{ aiText || 'AI 暂无更多建议' }}</view>
      </view>

      <view class="section">
        <view class="section-title">推荐医生</view>
        <view class="doctor-list">
          <view v-for="(doc, i) in result.doctors" :key="i" class="doctor-card">
            <image class="avatar" src="/static/images/nice/nice3.jpg" mode="aspectFill"></image>
            <view class="info">
              <view class="d1">{{ doc.name }} · {{ doc.title }}</view>
              <view class="d2">{{ doc.hospital }}</view>
              <view class="tags">
                <text class="tag" v-for="(t,ti) in doc.tags" :key="ti">{{ t }}</text>
              </view>
            </view>
            <button class="mini-btn" @click="consult(doc)">去咨询</button>
          </view>
        </view>
      </view>

      <view class="result-actions">
        <button class="ghost-btn" @click="restart">重新评估</button>
        <button class="primary-btn" @click="backHome">完成</button>
      </view>
    </view>
  </view>
</template>

<script>
import { chatSymptom } from '@/api/ai'
export default {
  data() {
    return {
      stage: 'welcome', // welcome | method | start | qa | result
      // 欢迎页图片（网络图，失败时回退到本地）
      welcomeImg: 'https://images.unsplash.com/photo-1584036561566-baf8f5f1b144?q=80&w=1080&auto=format&fit=crop',
      // 方式选择
      methodChoice: null, // ai | manual
      // 启动页：部位选择
      bodyParts: [
        { label: '头', value: 'head' },
        { label: '肩颈', value: 'shoulder' },
        { label: '手臂', value: 'arm' },
        { label: '腿', value: 'leg' },
        { label: '躯干/腹部', value: 'torso' }
      ],
      meta: { bodyPart: null },
      questions: [
        {
          id: 'pain_level',
          type: 'level',
          title: '请选择疼痛等级（1-5）',
          options: [
            { label: '（轻度）', value: '1' },
            { label: '（中度）', value: '2' },
            { label: '（伤疼）', value: '3' },
            { label: '（痛苦）', value: '4' },
            { label: '（严重）', value: '5' }
          ]
        },
        {
          id: 'main_symptom',
          type: 'single',
          title: '您现在最主要的不适是？',
          options: [
            { label: '发热', value: 'fever' },
            { label: '咳嗽', value: 'cough' },
            { label: '头痛', value: 'headache' },
            { label: '腹痛', value: 'abdominal_pain' },
            { label: '乏力', value: 'fatigue' },
            { label: '无', value: 'none' }
          ]
        },
        // 分支追问：按主诉显示
        {
          id: 'fever_temp',
          type: 'single',
          title: '最高体温大约是多少？',
          showIf: { id: 'main_symptom', anyOf: ['fever'] },
          options: [
            { label: '37.3-38.0℃', value: 'low' },
            { label: '38.1-39.0℃', value: 'mid' },
            { label: '≥39.1℃', value: 'high' }
          ]
        },
        {
          id: 'cough_type',
          type: 'single',
          title: '咳嗽类型更接近哪种？',
          showIf: { id: 'main_symptom', anyOf: ['cough'] },
          options: [
            { label: '干咳', value: 'dry' },
            { label: '咳痰', value: 'wet' },
            { label: '阵发性', value: 'paroxysmal' },
            { label: '夜间明显', value: 'night' }
          ]
        },
        {
          id: 'headache_location',
          type: 'single',
          title: '头痛特点更像哪种？',
          showIf: { id: 'main_symptom', anyOf: ['headache'] },
          options: [
            { label: '双侧箍紧感', value: 'band' },
            { label: '单侧搏动痛', value: 'migraine' },
            { label: '前额/面部憋胀', value: 'sinus' }
          ]
        },
        {
          id: 'abdominal_pain_area',
          type: 'single',
          title: '腹痛部位主要在哪里？',
          showIf: { id: 'main_symptom', anyOf: ['abdominal_pain'] },
          options: [
            { label: '右下腹', value: 'rlq' },
            { label: '上腹', value: 'epigastric' },
            { label: '脐周', value: 'periumbilical' },
            { label: '全腹', value: 'diffuse' }
          ]
        },
        {
          id: 'duration',
          type: 'single',
          title: '症状大约持续了多久？',
          options: [
            { label: '小于24小时', value: '<24h' },
            { label: '1-3天', value: '1-3d' },
            { label: '4-7天', value: '4-7d' },
            { label: '超过1周', value: '>1w' }
          ]
        },
        {
          id: 'aggravate',
          type: 'multiple',
          title: '是否存在加重或缓解因素？',
          desc: '可多选，如运动、受凉、饮水、休息等',
          options: [
            { label: '运动后加重', value: 'sport' },
            { label: '夜间加重', value: 'night' },
            { label: '休息后缓解', value: 'rest' },
            { label: '进食后加重', value: 'eat' },
            { label: '无明显变化', value: 'none' }
          ]
        },
        {
          id: 'companions',
          type: 'multiple',
          title: '是否伴随以下症状？',
          options: [
            { label: '咽痛', value: 'sore_throat' },
            { label: '流涕', value: 'runny_nose' },
            { label: '寒战', value: 'chills' },
            { label: '胸闷', value: 'chest_tight' },
            { label: '恶心', value: 'nausea' }
          ]
        }
      ],
      currentIndex: 0,
      firstActiveIndex: 0,
      answers: {}, // { [questionId]: [values] }
      inputValue: '',
      result: {
        score: 0,
        diseases: [],
        advices: [],
        doctors: []
      },
      // AI 分析报告
      aiText: '',
      aiLoading: false,
      aiError: null,
      aiMemoryId: null,
      aiTypingTimer: null
    }
  },
  onUnload() {
    // 页面卸载时清理打字机定时器
    if (this.aiTypingTimer) {
      clearInterval(this.aiTypingTimer)
      this.aiTypingTimer = null
    }
  },
  onLoad() {
    console.log('进入页面: /pages/ai/symptom/index')
    // 调试提示，确认已进入
    uni.showToast({ title: '症状评估已打开', icon: 'none', duration: 800 })
    // 确保用户资料已加载，以便后续请求可携带 userId
    this.ensureUserProfile()
  },
  computed: {
    // 仅返回满足 showIf 条件的可见题目
    visibleQuestions() {
      const isShown = (q) => {
        const cond = q.showIf
        if (!cond) return true
        const vals = Array.isArray(this.answers[cond.id]) ? this.answers[cond.id] : []
        if (Array.isArray(cond.anyOf)) {
          return vals.some(v => cond.anyOf.includes(v))
        }
        if (Array.isArray(cond.allOf)) {
          return cond.allOf.every(v => vals.includes(v))
        }
        return true
      }
      return this.questions.filter(isShown)
    },
    currentQuestion() {
      return this.visibleQuestions[this.currentIndex] || {}
    },
    bodyPartText() {
      const map = { head: '头部', shoulder: '肩部', arm: '手臂', leg: '腿部', torso: '躯干/腹部' }
      return map[this.meta.bodyPart] || ''
    },
    currentTitle() {
      if (this.currentQuestion && this.currentQuestion.id === 'pain_level') {
        return `按照 1-5 的等级，您的${this.bodyPartText}疼痛有多痛？`
      }
      return this.currentQuestion.title || ''
    },
    progress() {
      return Math.round(((this.currentIndex + 1) / this.visibleQuestions.length) * 100)
    },
    canNext() {
      const a = this.answers[this.currentQuestion.id]
      if (this.currentQuestion.type === 'input') {
        return !!this.inputValue.trim()
      }
      return Array.isArray(a) && a.length > 0
    },
    isLast() {
      return this.currentIndex === this.visibleQuestions.length - 1
    }
  },
  watch: {
    // 当答案变化导致题目显隐变化时，确保 currentIndex 合法
    answers: {
      deep: true,
      handler() {
        const len = this.visibleQuestions.length
        if (len <= 0) return
        if (this.currentIndex >= len) this.currentIndex = len - 1
        if (this.currentIndex < 0) this.currentIndex = 0
      }
    }
  },
  methods: {
    // 确保拉取到用户资料（含 userId）
    async ensureUserProfile() {
      try {
        const uid = this.$store && this.$store.getters && this.$store.getters.id
        if (!uid) {
          await this.$store.dispatch('GetInfo').catch(() => {})
        }
      } catch (e) { /* 忽略 */ }
    },
    // 欢迎页：开始评估
    startAssessment() {
      this.stage = 'method'
    },
    // 方式选择
    selectMethod(t) {
      this.methodChoice = t
    },
    continueFromMethod() {
      if (!this.methodChoice) return
      if (this.methodChoice === 'ai') {
        this.stage = 'start'
      } else if (this.methodChoice === 'manual') {
        // 跳转到AI对话页面
        uni.navigateTo({
          url: '/pages/ai/chat/index'
        })
      }
    },
    onWelcomeImgError() {
      this.welcomeImg = '/static/images/nice/new4.jpg'
    },
    // 启动页：选择身体部位后进入问答
    chooseBodyPart(v) {
      this.meta.bodyPart = v
      this.stage = 'qa'
      // 直接跳转到疼痛等级题目（仅在可见题目中定位）
      const idx = this.visibleQuestions.findIndex(q => q.id === 'pain_level')
      this.currentIndex = idx >= 0 ? idx : 0
      this.firstActiveIndex = this.currentIndex
    },
    // 浮动返回按钮：仅返回上一步，不返回首页
    fabBack() {
      switch (this.stage) {
        case 'method':
          this.stage = 'welcome'
          break
        case 'start':
          this.stage = 'method'
          break
        case 'qa':
          if (this.currentIndex === this.firstActiveIndex) {
            // 回到部位选择
            this.stage = 'start'
          } else {
            this.prev()
          }
          break
        case 'result':
          // 返回到问答页
          this.stage = 'qa'
          break
        case 'welcome':
        default:
          try {
            const pages = getCurrentPages && getCurrentPages()
            if (pages && pages.length > 1) {
              uni.navigateBack({ delta: 1 })
            } else {
              // 已经处于第一步，无更早页面
              uni.showToast({ title: '已经是第一步', icon: 'none' })
            }
          } catch (e) {
            uni.showToast({ title: '已经是第一步', icon: 'none' })
          }
      }
    },
    // 左侧按钮：首步返回，其余上一步
    onLeftClick() {
      if (this.currentIndex === this.firstActiveIndex) {
        uni.showModal({
          title: '退出评估',
          content: '确定要退出当前评估吗？',
          confirmText: '退出',
          cancelText: '继续',
          success: (res) => {
            if (res.confirm) this.backHome()
          }
        })
      } else {
        this.prev()
      }
    },
    // 选中判断（兼容小程序不支持可选链）
    isSelected(v) {
      const a = this.answers[this.currentQuestion.id]
      return Array.isArray(a) && a.indexOf(v) !== -1
    },
    // 单选
    chooseSingle(v) {
      this.$set(this.answers, this.currentQuestion.id, [v])
    },
    // 多选切换
    toggleMultiple(v) {
      const arr = this.answers[this.currentQuestion.id] ? [...this.answers[this.currentQuestion.id]] : []
      const i = arr.indexOf(v)
      if (i >= 0) arr.splice(i, 1)
      else arr.push(v)
      this.$set(this.answers, this.currentQuestion.id, arr)
    },
    // 渲染答案
    renderAnswer(vals) {
      const q = this.currentQuestion
      if (!q || !Array.isArray(vals)) return ''
      const map = {}
      ;(q.options || []).forEach(o => (map[o.value] = o.label))
      return vals.map(v => map[v] || v).join('，')
    },
    // 上一步
    prev() {
      if (this.currentIndex === this.firstActiveIndex) return
      this.currentIndex--
    },
    // 下一步/完成
    next() {
      if (this.currentQuestion.type === 'input') {
        this.$set(this.answers, this.currentQuestion.id, [this.inputValue.trim()])
        this.inputValue = ''
      }
      if (!this.isLast) {
        this.currentIndex++
      } else {
        this.generateResult()
        this.stage = 'result'
        // 评估完成后，请求 AI 分析报告
        this.queryAIAdvice()
      }
    },
    // 动态生成结果（基于用户选择的简单规则引擎）
    generateResult() {
      const get = (id) => (Array.isArray(this.answers[id]) ? this.answers[id] : [])
      const pick = (id, def = null) => {
        const a = get(id)
        return a.length ? a[0] : def
      }

      // 读取答案（按题目 id）
      const pain = parseInt(pick('pain_level', '3')) || 3 // 疼痛等级 1-5
      const main = pick('main_symptom', 'none') // 主要症状
      const duration = pick('duration', '1-3d') // 持续时间
      const aggravate = get('aggravate') // 加重/缓解
      const companions = get('companions') // 伴随
      // 分支追问
      const feverTemp = pick('fever_temp', null)
      const coughType = pick('cough_type', null)
      const headLoc = pick('headache_location', null)
      const abdArea = pick('abdominal_pain_area', null)

      // 1) 健康评分：根据疼痛/时程/伴随症状综合
      let severity = pain
      if (duration === '4-7d') severity += 0.5
      if (duration === '>1w') severity += 1
      if (companions.includes('chills')) severity += 1
      if (companions.includes('chest_tight')) severity += 1
      let score = Math.round(92 - severity * 4)
      if (duration === '<24h') score += 2
      score = Math.max(50, Math.min(95, score))

      // 2) 疾病推断（简单规则加权）
      const probs = {}
      const inc = (name, v) => {
        probs[name] = (probs[name] || 0) + v
      }

      // 基于主要症状的基线
      switch (main) {
        case 'fever':
          inc('上呼吸道感染', 55)
          inc('流感样疾病', 50)
          inc('普通感冒', 40)
          break
        case 'cough':
          inc('急性支气管炎', 55)
          inc('上呼吸道感染', 45)
          inc('过敏性咳嗽', 35)
          break
        case 'headache':
          inc('紧张性头痛', 50)
          inc('偏头痛', 45)
          inc('鼻窦炎', 35)
          break
        case 'abdominal_pain':
          inc('急性胃肠炎', 55)
          inc('胃炎/消化不良', 45)
          inc('阑尾炎待排', 30)
          break
        case 'fatigue':
          inc('病毒感染恢复期', 45)
          inc('贫血待排', 35)
          inc('甲状腺功能减退待排', 25)
          break
        default:
          inc('一般健康', 60)
          inc('轻度疲劳/压力', 45)
          inc('感冒前驱期', 30)
      }

      // 伴随症状修正
      if (companions.includes('runny_nose')) { inc('普通感冒', 12); inc('鼻窦炎', 8) }
      if (companions.includes('sore_throat')) { inc('上呼吸道感染', 12) }
      if (companions.includes('chills')) { inc('流感样疾病', 12) }
      if (companions.includes('chest_tight')) { inc('急性支气管炎', 10); inc('过敏性咳嗽', 6) }
      if (companions.includes('nausea')) { inc('急性胃肠炎', 12); inc('胃炎/消化不良', 8) }

      // 加重/缓解因素修正
      if (aggravate.includes('eat')) { inc('胃炎/消化不良', 12) }
      if (aggravate.includes('night')) { inc('过敏性咳嗽', 10) }
      if (aggravate.includes('rest')) { inc('上呼吸道感染', 4); inc('紧张性头痛', 4) }

      // 分支追问修正
      if (main === 'fever' && feverTemp) {
        if (feverTemp === 'high') { inc('流感样疾病', 14); inc('上呼吸道感染', 6) }
        if (feverTemp === 'mid') { inc('流感样疾病', 8) }
        if (feverTemp === 'low') { inc('普通感冒', 6) }
      }
      if (main === 'cough' && coughType) {
        if (coughType === 'dry') { inc('过敏性咳嗽', 12); inc('上呼吸道感染', 4) }
        if (coughType === 'wet') { inc('急性支气管炎', 12) }
        if (coughType === 'paroxysmal') { inc('过敏性咳嗽', 8) }
        if (coughType === 'night') { inc('过敏性咳嗽', 10) }
      }
      if (main === 'headache' && headLoc) {
        if (headLoc === 'band') { inc('紧张性头痛', 14) }
        if (headLoc === 'migraine') { inc('偏头痛', 14) }
        if (headLoc === 'sinus') { inc('鼻窦炎', 14) }
      }
      if (main === 'abdominal_pain' && abdArea) {
        if (abdArea === 'rlq') { inc('阑尾炎待排', 15) }
        if (abdArea === 'epigastric') { inc('胃炎/消化不良', 12) }
        if (abdArea === 'periumbilical') { inc('急性胃肠炎', 10) }
        if (abdArea === 'diffuse') { inc('急性胃肠炎', 8) }
      }

      // 疼痛/时程修正
      if (pain >= 4) { inc('阑尾炎待排', 6); inc('急性支气管炎', 6) }
      if (pain <= 2) { inc('一般健康', 6); inc('轻度疲劳/压力', 4) }
      if (duration === '>1w') { inc('过敏性咳嗽', 10); inc('胃炎/消化不良', 8); inc('紧张性头痛', 8) }
      if (duration === '<24h') { inc('上呼吸道感染', 6); inc('急性胃肠炎', 6) }

      // 转为列表、排序并限制为3项，同时标准化到百分比
      const sorted = Object.entries(probs)
        .map(([name, v]) => ({ name, score: Math.max(10, Math.min(95, Math.round(v))) }))
        .sort((a, b) => b.score - a.score)
        .slice(0, 3)

      const sum = sorted.reduce((s, it) => s + it.score, 0) || 1
      const diseases = sorted.map(it => ({ name: it.name, prob: Math.round((it.score / sum) * 100) }))

      // 3) 建议生成
      const advices = []
      advices.push('多饮水、注意休息，保持室内通风')
      if (main === 'fever') advices.push('间隔测量体温，物理降温为主，>38.5℃谨遵医嘱退烧')
      if (main === 'cough') advices.push('避免受凉与刺激性气味，必要时在医生指导下对症用药')
      if (main === 'abdominal_pain') advices.push('清淡饮食，暂避油腻辛辣，注意补液')
      if (main === 'headache') advices.push('规律作息，减少屏幕时间，必要时安静环境休息')
      if (main === 'fever' && feverTemp === 'high') advices.push('高热明显，注意物理降温并尽快就诊')
      if (main === 'abdominal_pain' && abdArea === 'rlq') advices.push('右下腹剧痛提示阑尾炎可能，尽快就医')
      if (duration === '>1w' || pain >= 4 || companions.includes('chest_tight')) {
        advices.push('症状较重或持续时间较长，建议尽快至医院就诊')
      }

      // 4) 推荐医生（按专科）
      const mainMap = {
        fever: '发热', cough: '咳嗽', headache: '头痛', abdominal_pain: '腹痛', fatigue: '乏力', none: '一般'
      }
      let dept = '全科门诊'
      if (['fever', 'cough'].includes(main)) dept = '呼吸内科'
      if (main === 'abdominal_pain') dept = '消化内科'
      if (main === 'headache') dept = '神经内科'

      const doctors = [
        { name: '王医生', title: '主治医师', hospital: `市人民医院 ${dept}`, tags: [dept, mainMap[main] || '咨询'] },
        { name: '李医生', title: '副主任医师', hospital: `市中医院 ${dept === '全科门诊' ? '全科' : dept}` , tags: [dept, '用药指导'] }
      ]

      this.result = { score, diseases, advices, doctors }
    },
    // 构建发送给后端AI的问诊摘要
    buildPromptForAI() {
      const get = (id) => (Array.isArray(this.answers[id]) ? this.answers[id] : [])
      const labelOf = (qid, val) => {
        const q = this.questions.find(x => x.id === qid)
        if (!q || !Array.isArray(q.options)) return val
        const found = q.options.find(o => o.value === val)
        return found ? found.label : val
      }
      const pickLabel = (qid, def = '') => {
        const a = get(qid)
        if (!a.length) return def
        return a.map(v => labelOf(qid, v)).join('、')
      }

      const bodyPartMap = { head: '头部', shoulder: '肩颈', arm: '手臂', leg: '腿', torso: '躯干/腹部' }
      const bodyPart = bodyPartMap[this.meta.bodyPart] || '未选择'

      const mainSymptom = pickLabel('main_symptom', '未选择')
      const painLevel = pickLabel('pain_level', '未选择')
      const duration = pickLabel('duration', '未选择')
      const aggravate = pickLabel('aggravate', '无')
      const companions = pickLabel('companions', '无')
      const feverTemp = pickLabel('fever_temp', '')
      const coughType = pickLabel('cough_type', '')
      const headacheLoc = pickLabel('headache_location', '')
      const abdArea = pickLabel('abdominal_pain_area', '')

      const details = []
      details.push(`主要不适部位：${bodyPart}`)
      details.push(`主要症状：${mainSymptom}`)
      details.push(`疼痛/不适等级：${painLevel}`)
      details.push(`症状持续时间：${duration}`)
      if (aggravate && aggravate !== '无') details.push(`加重/缓解因素：${aggravate}`)
      if (companions && companions !== '无') details.push(`伴随症状：${companions}`)
      if (feverTemp) details.push(`最高体温：${feverTemp}`)
      if (coughType) details.push(`咳嗽类型：${coughType}`)
      if (headacheLoc) details.push(`头痛特点：${headacheLoc}`)
      if (abdArea) details.push(`腹痛部位：${abdArea}`)

      const instruction = [
        '你是一名严谨的全科医生助理。基于以下用户自报信息，生成面向患者的中文评估报告：',
        '1) 可能的疾病或问题（最多3项，含简短解释和发生概率区间，避免过度诊断）。',
        '2) 何时需要立即就医的红旗提示（如出现哪些症状或体征需要急诊）。',
        '3) 居家处理与生活方式建议（3-5条，具体可执行）。',
        '4) 用药建议请务必谨慎，避免具体处方，仅可提示“需在医生指导下使用”类别用药。',
        '5) 严格标注免责声明：本结果仅供参考，不能替代医生面诊。'
      ].join('\n')

      return `${instruction}\n\n【用户基本信息与主诉】\n${details.join('\n')}\n\n【报告格式要求】\n- 使用清晰的小标题与条目\n- 尽量通俗易懂\n- 控制在300-500字`
    },
    // 请求后端AI，生成分析报告
    async queryAIAdvice() {
      try {
        this.aiLoading = true
        this.aiError = null
        // 再次确保用户资料可用（若从其他入口进入未触发 onLoad 时）
        await this.ensureUserProfile()
        const prompt = this.buildPromptForAI()
        const resp = await chatSymptom(prompt, this.aiMemoryId)
        // 文本响应由 request.js 包装为 { code:200, data: string }
        let text = typeof resp === 'string' ? resp : (resp && resp.data ? resp.data : '')
        
        // 替换AI回复中的固定姓名为当前用户姓名
        text = this.replaceUserName(text)
        
        const finalText = text || 'AI暂无更多建议'
        // 使用打字机效果渐进展示
        this.typeWrite(finalText)
      } catch (e) {
        console.error('queryAIAdvice error:', e)
        this.aiError = 'AI建议生成失败，请稍后重试'
      } finally {
        this.aiLoading = false
      }
    },
    // 打字机效果：逐步渲染文本
    typeWrite(fullText) {
      if (this.aiTypingTimer) {
        clearInterval(this.aiTypingTimer)
        this.aiTypingTimer = null
      }
      this.aiText = ''
      let i = 0
      const step = 3 // 每次追加字符数
      this.aiTypingTimer = setInterval(() => {
        // 如果离开结果页，停止
        if (this.stage !== 'result') {
          clearInterval(this.aiTypingTimer)
          this.aiTypingTimer = null
          return
        }
        this.aiText += fullText.slice(i, i + step)
        i += step
        if (i >= fullText.length) {
          clearInterval(this.aiTypingTimer)
          this.aiTypingTimer = null
        }
      }, 20)
    },
    // 结果动作
    restart() {
      this.stage = 'start'
      this.currentIndex = 0
      this.answers = {}
      this.meta.bodyPart = null
      this.result = { score: 0, diseases: [], advices: [], doctors: [] }
      // 清空 AI 状态
      this.aiText = ''
      this.aiError = null
      this.aiLoading = false
      this.aiMemoryId = null
      if (this.aiTypingTimer) {
        clearInterval(this.aiTypingTimer)
        this.aiTypingTimer = null
      }
    },
    backHome() {
      try {
        const pages = getCurrentPages && getCurrentPages()
        if (pages && pages.length > 1) {
          uni.navigateBack({ delta: 1 })
        } else {
          // 无历史时返回到 AI 助手 tab
          uni.switchTab({ url: '/pages/consult/ai' })
        }
      } catch (e) {
        uni.switchTab({ url: '/pages/consult/ai' })
      }
      if (this.aiTypingTimer) {
        clearInterval(this.aiTypingTimer)
        this.aiTypingTimer = null
      }
    },
    consult(doc) {
      // 这里仅提示，真实项目可跳转到医生详情/图文咨询
      uni.showToast({ title: `咨询 ${doc.name}`, icon: 'none' })
    },

    // 替换AI回复中的固定姓名为当前用户姓名
    replaceUserName(aiReply) {
      try {
        // 获取当前用户姓名
        const userName = this.$store.getters.name || '用户'
        
        // 替换常见的固定姓名模式
        let processedReply = aiReply
        
        // 替换 "赵云飞先生" 为用户名
        processedReply = processedReply.replace(/赵云飞先生/g, `${userName}`)
        
        // 替换其他可能的固定姓名模式
        processedReply = processedReply.replace(/赵云飞/g, userName)
        
        return processedReply
      } catch (error) {
        console.error('替换用户姓名时出错:', error)
        return aiReply
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 背景与全局间距 */
.symptom-container {
  min-height: 100vh;
  padding-bottom: env(safe-area-inset-bottom);
  background: linear-gradient(180deg, #f8fafc 0%, #f4f7fb 100%);
}

/* 方式选择页 */
.method-page { padding: 32rpx 24rpx 200rpx; }
.steps {
  display: flex; gap: 20rpx; align-items: center; padding: 8rpx 6rpx;
}
.step {
  width: 64rpx; height: 16rpx; border-radius: 20rpx; background: #e5e7eb;
}
.step.active { background: linear-gradient(90deg, #22c1c3, #2bd3be); }
.method-title {
  margin: 24rpx 8rpx 16rpx; font-size: 44rpx; font-weight: 800; color: #111827; line-height: 1.4;
}
.method-cards { display: flex; flex-direction: column; gap: 20rpx; margin-top: 12rpx; }
.method-card {
  background: #f6f9ff; border: 2rpx solid #e5e7eb; border-radius: 16rpx; padding: 26rpx;
}
.method-card .card-icon { width: 72rpx; height: 72rpx; border-radius: 18rpx; background: #ecfeff; color: #0891b2; display: flex; align-items: center; justify-content: center; font-size: 36rpx; box-shadow: 0 6rpx 16rpx rgba(8,145,178,0.08); }
.method-card .card-title { margin-top: 12rpx; font-size: 32rpx; font-weight: 700; color: #111827; }
.method-card .card-desc { margin-top: 6rpx; color: #6b7280; font-size: 26rpx; }
.method-card.active { background: #e6fbf8; border-color: #99f6e4; box-shadow: 0 10rpx 20rpx rgba(16,185,129,0.12); }

/* 欢迎页 */
.welcome-page {
  padding: 32rpx 32rpx 120rpx;
  text-align: center;
}
.welcome-back {
  width: 64rpx;
  height: 64rpx;
  border-radius: 16rpx;
  background: #ffffff;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 18rpx rgba(0,0,0,0.06);
  color: #111827;
}
.welcome-hero {
  width: 100%;
  margin-top: 40rpx;
  border-radius: 24rpx;
  box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.06);
}
.welcome-hero-wrap { position: relative; }
.hero-fab {
  position: absolute; left: 20rpx; bottom: 20rpx;
  width: 88rpx; height: 88rpx; border-radius: 22rpx; background: #111827;
  display: flex; align-items: center; justify-content: center; box-shadow: 0 12rpx 24rpx rgba(0,0,0,0.14);
}
.welcome-title {
  margin-top: 36rpx;
  font-size: 44rpx;
  font-weight: 800;
  color: #111827;
}
.welcome-subtitle {
  margin-top: 12rpx;
  color: #6b7280;
  font-size: 26rpx;
}
.welcome-btn {
  width: 80%;
  margin: 36rpx auto 0;
}

/* 启动页 - 卡片化视觉 */
.start-page {
  padding: 32rpx 32rpx 200rpx;
}
.start-header { height: 72rpx; display: flex; align-items: center; }
.logo-mark {
  width: 64rpx; height: 64rpx; border-radius: 18rpx;
  border: 4rpx solid #19c1b6; position: relative;
}
.logo-mark::before, .logo-mark::after {
  content: '';
  position: absolute;
  background: #19c1b6;
  border-radius: 8rpx;
}
.logo-mark::before { width: 8rpx; height: 36rpx; left: 50%; top: 14rpx; transform: translateX(-50%); }
.logo-mark::after { height: 8rpx; width: 36rpx; left: 14rpx; top: 50%; transform: translateY(-50%); }
.start-title {
  margin-top: 24rpx;
  font-size: 40rpx; line-height: 1.4;
  font-weight: 800; color: #111827;
  width: 80%;
}
.start-options { margin-top: 26rpx; display: flex; flex-direction: column; gap: 18rpx; }
.start-option {
  background: #f3f6fb; color: #1f2937; border: 2rpx solid #e5e7eb;
  height: 92rpx; line-height: 92rpx; padding: 0 26rpx; border-radius: 999rpx;
  display: flex; align-items: center; justify-content: space-between;
  font-size: 30rpx;
}
.start-option .arrow { color: #9ca3af; font-weight: 700; }
.start-option:active { background: linear-gradient(90deg, #22c1c3, #2bd3be); color: #fff; border-color: transparent; }
.start-option:active .arrow { color: #fff; }
.fab {
  position: fixed; left: 32rpx; bottom: calc(32rpx + env(safe-area-inset-bottom));
  width: 88rpx; height: 88rpx; border-radius: 22rpx; background: #111827;
  display: flex; align-items: center; justify-content: center; box-shadow: 0 12rpx 24rpx rgba(0,0,0,0.14);
  z-index: 20;
}
.back-icon { color: #ffffff; font-size: 44rpx; line-height: 1; }
.start-page .hero {
  width: 100%;
  height: 360rpx;
  border-radius: 20rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.06);
}
.start-page .title {
  margin-top: 28rpx;
  font-size: 42rpx;
  font-weight: 700;
  color: #1f2937;
  text-align: center;
}
.start-page .subtitle {
  margin-top: 10rpx;
  color: #6b7280;
  font-size: 26rpx;
  text-align: center;
}
.intro-dots { display: flex; justify-content: center; gap: 12rpx; margin: 18rpx 0 6rpx; }
.intro-dots .dot { width: 12rpx; height: 12rpx; border-radius: 999rpx; background: #e5e7eb; transition: all .25s ease; }
.intro-dots .dot.active { width: 36rpx; background: linear-gradient(90deg, #22c1c3, #2bd3be); }
.primary-btn {
  margin-top: 24rpx;
  height: 88rpx;
  line-height: 88rpx;
  border: none;
  border-radius: 999rpx;
  color: #fff;
  font-size: 30rpx;
  font-weight: 600;
  background: linear-gradient(90deg, #22c1c3, #2bd3be);
  box-shadow: 0 10rpx 24rpx rgba(43, 211, 190, 0.35);
}
.ghost-btn {
  background: #fff;
  color: #16a085;
  border: 2rpx solid #c7f2ec;
  border-radius: 999rpx;
}
.tips {
  margin-top: 18rpx;
  color: #9ca3af;
  font-size: 22rpx;
  text-align: center;
}

/* 启动页底栏，与其他页面完全一致 */
.start-footer {
  position: fixed;
  left: 0; right: 0; bottom: 0;
  padding: 16rpx 20rpx calc(16rpx + env(safe-area-inset-bottom));
  background: #ffffff; display: flex; gap: 24rpx;
  border-top: 2rpx solid #eef2f7;
  justify-content: space-between;
  align-items: center;
  z-index: 10;
}
.start-footer .btn-spacer { width: 260rpx; height: 88rpx; }
.start-footer .primary-btn {
  width: 260rpx; height: 88rpx; line-height: 88rpx; border-radius: 999rpx;
  margin: 0; padding: 0; box-sizing: border-box;
  display: flex; align-items: center; justify-content: center;
  font-size: 30rpx; font-weight: 600;
  border: 2rpx solid transparent;
}
.start-footer .primary-btn[disabled] {
  background: #e5f6f4; color: #9ca3af; box-shadow: none;
}
.start-footer .ghost-btn {
  width: 260rpx; height: 88rpx; line-height: 88rpx; border-radius: 999rpx;
  margin: 0; padding: 0; box-sizing: border-box;
  display: flex; align-items: center; justify-content: center;
  font-size: 30rpx; font-weight: 600;
}

/* 问答页 */
.qa-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.qa-header {
  padding: 22rpx 28rpx 18rpx;
  background: #ffffff;
  border-bottom: 2rpx solid #eef2f7;
}
.progress-text {
  font-size: 24rpx;
  color: #6b7280;
  margin-bottom: 12rpx;
}
.progress {
  height: 12rpx;
  background: #eef2f7;
  border-radius: 999rpx;
  overflow: hidden;
}
.bar {
  height: 100%;
  background: linear-gradient(90deg, #22c1c3, #2bd3be);
}
.qa-body {
  flex: 1;
  padding: 24rpx 28rpx 200rpx;
}

/* 气泡 */
.bubble { display: flex; gap: 18rpx; margin-bottom: 22rpx; }
.bubble-avatar {
  width: 64rpx; height: 64rpx; border-radius: 50%;
  background: #ecfeff; color: #0891b2;
  display: flex; align-items: center; justify-content: center;
  box-shadow: 0 6rpx 16rpx rgba(8,145,178,0.08);
}
.bubble-content {
  max-width: 560rpx; padding: 20rpx 22rpx; border-radius: 18rpx;
  font-size: 28rpx; line-height: 1.5; background: #ffffff;
  border: 2rpx solid #eef2f7;
}
.bubble.ai .bubble-content { background: #ffffff; }
.bubble.user { flex-direction: row-reverse; }
.bubble.user .bubble-content {
  background: linear-gradient(135deg, #22c1c3, #2bd3be);
  color: #fff; border-color: transparent;
}
.q-title { font-weight: 700; color: #111827; margin-bottom: 10rpx; }
.q-desc { color: #6b7280; font-size: 24rpx; margin-bottom: 16rpx; }

/* 选项 - 胶囊样式 */
.options { display: flex; flex-wrap: wrap; gap: 16rpx; }
.option {
  background: #f3f6fb; color: #374151; border: 2rpx solid #e5e7eb;
  height: 72rpx; line-height: 72rpx; padding: 0 28rpx;
  min-width: 168rpx; text-align: center;
  border-radius: 999rpx; font-size: 28rpx;
}
.option.active {
  background: #e6fbf8; color: #0f766e; border-color: #99f6e4;
  box-shadow: 0 8rpx 18rpx rgba(16,185,129,0.15);
}
.level-list { display: flex; flex-direction: column; gap: 12rpx; margin-top: 10rpx; }
.level-item {
  display: flex; align-items: center; gap: 16rpx;
  background: #f3f6fb; border: 2rpx solid #e5e7eb; border-radius: 20rpx;
  padding: 18rpx 22rpx;
}
.level-item .badge {
  width: 52rpx; height: 52rpx; border-radius: 14rpx;
  background: #eafaf7; color: #0f766e; font-weight: 700;
  display: flex; align-items: center; justify-content: center;
}
.level-item .text { color: #374151; font-size: 28rpx; }
.level-item.active {
  background: linear-gradient(135deg, #22c1c3, #2bd3be);
  border-color: transparent; box-shadow: 0 12rpx 24rpx rgba(34, 193, 195, 0.25);
}
.level-item.active .text { color: #ffffff; }
.level-item.active .badge { background: rgba(255,255,255,0.25); color: #ffffff; }
.input-wrap { margin-top: 10rpx; }
.text-input {
  background: #f3f6fb; padding: 18rpx 22rpx; border-radius: 14rpx;
  font-size: 28rpx; border: 2rpx solid #e5e7eb;
}

.qa-footer {
  position: fixed;
  left: 0; right: 0; bottom: 0;
  padding: 16rpx 20rpx calc(16rpx + env(safe-area-inset-bottom));
  background: #ffffff; display: flex; gap: 24rpx;
  border-top: 2rpx solid #eef2f7;
  justify-content: space-between;
  align-items: center;
  z-index: 10;
}
.qa-footer .ghost-btn,
.qa-footer .primary-btn {
  width: 260rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 999rpx;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  display: flex; align-items: center; justify-content: center;
  font-size: 30rpx; font-weight: 600;
}
.qa-footer .primary-btn { border: 2rpx solid transparent; }
.qa-footer .ghost-btn[disabled] {
  background: #ffffff;
  color: #8fd9d2;
  border-color: #e6fbf8;
  opacity: 1;
}
.qa-footer .primary-btn[disabled] {
  background: #e5f6f4;
  color: #9ca3af;
  box-shadow: none;
}

/* 结果页 */
.result-page { padding: 20rpx 24rpx 200rpx; }
.score-card {
  background: linear-gradient(180deg, #f0fffd, #ffffff);
  border: 2rpx solid #d9f8f3; border-radius: 18rpx; padding: 28rpx;
  text-align: center; box-shadow: 0 10rpx 24rpx rgba(34, 193, 195, 0.08);
}
.score { font-size: 72rpx; font-weight: 800; color: #0f766e; }
.score-label { margin-top: 6rpx; color: #4b5563; }
.score-desc { margin-top: 6rpx; color: #9ca3af; font-size: 24rpx; }
.section { margin-top: 24rpx; background: #fff; border-radius: 16rpx; padding: 22rpx; border: 2rpx solid #eef2f7; }
.section-title { font-weight: 700; margin-bottom: 12rpx; color: #111827; }
.disease-item { margin: 16rpx 0; }
.prob { position: relative; height: 14rpx; background: #eef2f7; border-radius: 14rpx; overflow: hidden; }
.prob-bar { height: 100%; background: linear-gradient(90deg,#22c1c3,#2bd3be); }
.prob-text { position: absolute; top: -36rpx; right: 0; font-size: 22rpx; color: #6b7280; }
.advice { color: #374151; font-size: 26rpx; margin: 8rpx 0; white-space: pre-line; }
.doctor-list { display: flex; flex-direction: column; gap: 16rpx; }
.doctor-card { display: flex; gap: 16rpx; background: #f9fbfb; border: 2rpx solid #d9f8f3; border-radius: 14rpx; padding: 16rpx; align-items: center; }
.avatar { width: 96rpx; height: 96rpx; border-radius: 12rpx; background: #eee; }
.info { flex: 1; }
.d1 { font-weight: 700; color: #111827; }
.d2 { color: #6b7280; font-size: 24rpx; margin-top: 4rpx; }
.tags { display: flex; gap: 8rpx; flex-wrap: wrap; margin-top: 6rpx; }
.tag { background: #e6fbf8; color: #0f766e; padding: 6rpx 12rpx; border-radius: 999rpx; font-size: 22rpx; border: 2rpx solid #99f6e4; }
.mini-btn { background: linear-gradient(90deg,#22c1c3,#2bd3be); color: #fff; border: none; font-size: 24rpx; border-radius: 999rpx; }
.result-actions {
  position: fixed;
  left: 0; right: 0; bottom: 0;
  background: #ffffff;
  border-top: 2rpx solid #eef2f7;
  display: flex;
  gap: 24rpx;
  justify-content: space-between;
  padding: 16rpx 20rpx calc(16rpx + env(safe-area-inset-bottom));
  align-items: center;
  z-index: 10;
}
.result-actions .ghost-btn,
.result-actions .primary-btn {
  width: 260rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 999rpx;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  display: flex; align-items: center; justify-content: center;
  font-size: 30rpx; font-weight: 600;
}
.result-actions .primary-btn { border: 2rpx solid transparent; }

/* 移除小程序按钮默认描边，避免视觉位移 */
.start-footer .ghost-btn::after,
.start-footer .primary-btn::after,
.start-option::after,
.qa-footer .ghost-btn::after,
.qa-footer .primary-btn::after,
.result-actions .ghost-btn::after,
.result-actions .primary-btn::after {
  border: none;
}
</style>
